from __future__ import absolute_import
#import logging
from os.path import exists
from forest.api import Command, get_tool

# TODO: Err if components are missing
class CreateRaid(Command):
    ''' Creates raid devices from raid resources.
    '''
    __register__ = 'commands.install.Raid'

    requires_config = ['install_mode'] #, 'raid'

    def run(self, config):
        #raid_devices = config.get_type(RAIDS, 'raid', False)

        # install_tree = config.get_install_root()

        raid = list(config.get_resources().iter_by_type('raid'))

        # only create raids if we have to
        if not raid:
            return

        #if there exist raid devices, turn off rebuilding of them all the time
        if not config.is_dry_run():
            get_tool('files.write')('/proc/sys/dev/raid/speed_limit_min', '0')
            get_tool('files.write')('/proc/sys/dev/raid/speed_limit_max', '0')

        for device in raid:
            r = device

            for comp in r.get_components():
                if not exists('/dev/%s' % comp):
                    raise Exception("Missing raid component: %s" % comp)

            get_tool('system.execute')(['mdadm', '--stop', r.get_name()])
            get_tool('raid.create_raid')(r.get_name(), r.get_level(), r.get_components(), r.get_metadata())

        get_tool('parted.probe')
        get_tool('udev.settle')
        print open('/proc/mdstat').read()
